<template>
  <div class="temperature-forecast-container">
    <div class="header">
      <h2>桂林未来温度预测</h2>
      <div class="controls">
        <el-select v-model="selectedModel" placeholder="选择预测模型" @change="handleModelChange">
          <el-option label="Ensemble" value="Ensemble"></el-option>
          <el-option label="LSTM" value="LSTM"></el-option>
        </el-select>
        <el-select v-model="selectedTarget" placeholder="选择预测目标">
          <el-option v-if="selectedModel === 'Ensemble'" label="最高温度" value="guilin_max"></el-option>
          <el-option v-if="selectedModel === 'Ensemble'" label="最低温度" value="guilin_min"></el-option>
          <el-option v-if="selectedModel === 'LSTM'" label="平均温度" value="guilin_temp"></el-option>
        </el-select>
        <el-input-number 
          v-model="predictionDays" 
          :min="1" 
          :max="180" 
          :disabled="selectedModel === 'LSTM'"
          :value="selectedModel === 'LSTM' ? 90 : predictionDays"
          @change="selectedModel === 'LSTM' ? null : handleDaysChange"
          placeholder="请输入预测天数" 
        />
        <el-button type="primary" :loading="isLoading" @click="fetchTemperatureData" icon="el-icon-refresh">
          获取预测
        </el-button>
      </div>
    </div>

    <div class="content-wrapper">
      <div v-if="error" class="error-message">
        <el-alert :title="error" type="error" show-icon :closable="true" @close="error = ''" />
      </div>

      <template v-else>
        <div class="response-section">
          <div class="response-header">
            <h3>API响应数据：
              <span v-if="apiResponse.prediction_days" class="predicted_days">
                {{ apiResponse.prediction_days }}天
              </span>
            </h3>
            <div class="response-meta">
              <el-tag :type="responseStatusType" size="medium">
                {{ apiResponse.status || 'unknown' }}
              </el-tag>
              <span class="response-time" v-if="responseTime">
                响应时间: {{ (responseTime / 1000).toFixed(2) }}s
              </span>
            </div>
          </div>

          <div class="response-data">
            <div class="forecast-details-container">
              <el-collapse v-model="activeCollapse">
                <el-collapse-item title="预测数据详情" name="predictions">
                  <el-table :data="tableData" border style="width: 100%" :max-height="300">
                    <el-table-column prop="date" label="日期" width="180" sortable />
                    <el-table-column prop="temperature" label="温度 (°C)" width="120" sortable />
                  </el-table>
                </el-collapse-item>
              </el-collapse>
            </div>
            <div class="monthly-average-container">
              <el-collapse v-model="activeCollapse">
                <el-collapse-item title="每月平均气温" name="monthlyAverage">
                  <el-table :data="monthlyTableData" border style="width: 100%;">
                    <el-table-column prop="month" label="月份" width="120" />
                    <el-table-column prop="averageTemperature" label="平均温度 (°C)" width="140" />
                  </el-table>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>

        <div class="chart-section">
          <div class="chart-container" ref="chartContainer"></div>
          <div class="chart-legend">
            <div class="legend-item">
              <span class="legend-color" style="background-color: #36a3f7;"></span>
              <span class="legend-text">预测温度 (°C)</span>
            </div>
          </div>
        </div>

        <!-- 历史数据对比图表部分 -->
        <div class="historical-comparison-section">
          <div class="chart-controls">
            <el-select v-model="selectedMonth" placeholder="选择月份" @change="fetchHistoricalData">
              <el-option v-for="month in availableMonths" :key="month" :label="month" :value="month"></el-option>
            </el-select>
            <el-button type="primary" @click="fetchHistoricalData" :loading="isLoadingHistorical">
              加载历史数据
            </el-button>
          </div>

          <div class="chart-container" ref="historicalChartContainer"></div>
          <div class="chart-legend">
            <div class="legend-item" v-for="(color, year) in historicalChartColors" :key="year">
              <span class="legend-color" :style="{ backgroundColor: color }"></span>
              <span class="legend-text">{{ year }}年</span>
            </div>
            <div class="legend-item prediction">
              <span class="legend-color" :style="{ backgroundColor: predictionColor }"></span>
              <span class="legend-text">预测数据</span>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import { debounce } from 'lodash';
import { fetchTemperaturePredictions } from '../api/predict_ensemble';
import { fetchLSTMTemperaturePredictions } from '../api/predict_lstm';
import { getHistoricalWeatherForPredictionComparison } from '../api/get_historical_data';

export default {
  name: 'TemperatureForecast',
  data() {
    return {
      apiBaseUrl: 'http://127.0.0.1:5000/api',
      selectedModel: 'Ensemble',
      selectedTarget: 'guilin_max',
      predictionDays: 30,
      isLoading: false,
      error: '',
      activeCollapse: ['predictions', 'monthlyAverage'],
      responseTime: null,
      apiResponse: {
        status: '',
        model: '',
        predictions: [],
        plot_url: '',
        last_training_date: '',
        execution_time: '',
        statistics: {
          average: 0,
          max: 0,
          min: 0
        },
        prediction_days: 0,
        target_column: ''
      },
      chartInstance: null,
      historicalChartInstance: null,
      resizeHandler: null,
      isChartDataReady: false,
      availableMonths: [],
      selectedMonth: '',
      isLoadingHistorical: false,
      historicalData: {},
      historicalChartColors: {},
      predictionColor: '#ff0000',
      lstmTempField: 'temperature' // LSTM模型使用的温度字段名
    };
  },
  computed: {
    responseStatusType() {
      return this.apiResponse.status === 'success' ? 'success' : 'danger';
    },
    hasValidData() {
      return (
        this.apiResponse.status === 'success' &&
        this.apiResponse.predictions &&
        this.apiResponse.predictions.length > 0
      );
    },
    normalizedPredictions() {
      if (!this.hasValidData) return [];
      
      // 根据模型类型选择温度字段
      const field = this.selectedModel === 'LSTM' 
        ? this.lstmTempField 
        : this.selectedTarget;
      
      return this.apiResponse.predictions.map(item => {
        const date = dayjs(item.date).format('YYYY-MM-DD');
        const temperature = parseFloat(item[field] || 0);
        
        if (isNaN(temperature)) {
          console.warn(`Invalid temperature value for date ${date}:`, item[field]);
          return { date, temperature: 0 };
        }
        
        return { date, temperature };
      });
    },
    tableData() {
      return this.normalizedPredictions.map(item => ({
        ...item,
        temperature: item.temperature.toFixed(1)
      }));
    },
    monthlyAverageTemperatures() {
      if (!this.hasValidData) return {};

      const monthlyData = {};
      this.normalizedPredictions.forEach(item => {
        const date = dayjs(item.date);
        const monthKey = date.format('YYYY-MM');
        const monthName = date.format('YYYY年MM月');

        if (!monthlyData[monthKey]) {
          monthlyData[monthKey] = {
            monthName,
            sum: 0,
            count: 0
          };
        }

        monthlyData[monthKey].sum += item.temperature;
        monthlyData[monthKey].count++;
      });

      return Object.entries(monthlyData).reduce((acc, [monthKey, data]) => {
        acc[monthKey] = {
          month: data.monthName,
          averageTemperature: (data.sum / data.count).toFixed(1)
        };
        return acc;
      }, {});
    },
    monthlyTableData() {
      return Object.values(this.monthlyAverageTemperatures).sort((a, b) =>
        dayjs(a.month, 'YYYY年MM月').diff(dayjs(b.month, 'YYYY年MM月'))
      );
    },
    extractAvailableMonths() {
      if (!this.hasValidData) return [];

      const monthsSet = new Set();
      this.normalizedPredictions.forEach(item => {
        const date = dayjs(item.date);
        monthsSet.add(date.format('YYYY-MM'));
      });

      return Array.from(monthsSet).sort((a, b) => dayjs(a).diff(dayjs(b)));
    }
  },
  watch: {
    apiResponse: {
      deep: true,
      handler() {
        this.availableMonths = this.extractAvailableMonths;
        if (this.availableMonths.length > 0) {
          this.selectedMonth = this.availableMonths[0];
        }
      }
    },
    selectedModel(newVal, oldVal) {
      if (newVal === 'LSTM') {
        this.$message({
          type: 'info',
          message: 'LSTM模型是基于长期时间序列预测的，预测天数固定为90天，且只提供平均温度预测',
          duration: 5000
        });
      }
    },
    // 监听数据准备状态，触发图表渲染
    normalizedPredictions() {
      if (this.normalizedPredictions.length > 0) {
        this.isChartDataReady = true;
        this.renderTemperatureChart();
      }
    }
  },
  mounted() {
    this.initCharts();
    this.setupResizeHandler();
  },
  beforeUnmount() {
    this.removeResizeHandler();
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
    if (this.historicalChartInstance) {
      this.historicalChartInstance.dispose();
      this.historicalChartInstance = null;
    }
  },
  methods: {
    initCharts() {
      if (!this.$refs.chartContainer) return;
      this.chartInstance = echarts.init(this.$refs.chartContainer);

      if (!this.$refs.historicalChartContainer) return;
      this.historicalChartInstance = echarts.init(this.$refs.historicalChartContainer);

      window.addEventListener('resize', this.handleResize);
    },
    setupResizeHandler() {
      this.resizeHandler = debounce(() => {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
        if (this.historicalChartInstance) {
          this.historicalChartInstance.resize();
        }
      }, 300);
      window.addEventListener('resize', this.resizeHandler);
    },
    removeResizeHandler() {
      if (this.resizeHandler) {
        window.removeEventListener('resize', this.resizeHandler);
      }
    },
    handleModelChange() {
      if (this.selectedModel === 'LSTM') {
        this.predictionDays = 90;
        this.selectedTarget = 'guilin_temp';
      } else {
        this.predictionDays = 30;
        this.selectedTarget = 'guilin_max';
      }
    },
    async fetchTemperatureData() {
      this.isLoading = true;
      this.error = '';
      this.isChartDataReady = false;
      const startTime = Date.now();

      try {
        let response;
        if (this.selectedModel === 'Ensemble') {
          response = await fetchTemperaturePredictions(this.predictionDays, this.selectedTarget);
          
          // 确保数据格式正确
          if (!response.predictions || typeof response.predictions !== 'object') {
            throw new Error('Ensemble模型返回的数据格式不正确');
          }
          
          // 统一转换为 {date, temperature} 结构
          response.predictions = Object.entries(response.predictions).map(([date, temp]) => ({
            date,
            [this.selectedTarget]: temp
          }));
        } else if (this.selectedModel === 'LSTM') {
          response = await fetchLSTMTemperaturePredictions();
          
          // 打印原始数据用于调试
          console.log('LSTM原始响应:', response);
          
          // 验证LSTM数据格式
          if (!Array.isArray(response.predictions)) {
            throw new Error('LSTM模型返回的数据格式不正确');
          }
          
          // 确保每个预测项包含日期和温度字段
          response.predictions = response.predictions.map(item => ({
            date: item.date,
            [this.lstmTempField]: item[this.lstmTempField]
          }));
        }

        this.responseTime = Date.now() - startTime;

        if (!response || !response.predictions) {
          throw new Error('服务器返回空数据或格式错误');
        }

        this.validateResponseData(response);
        this.processResponseData(response);
        
        // 确保DOM和数据都更新后再渲染图表
        this.$nextTick(() => {
          this.renderTemperatureChart();
          
          if (this.availableMonths.length > 0) {
            this.selectedMonth = this.availableMonths[0];
            this.fetchHistoricalData();
          }
        });

      } catch (error) {
        this.handleRequestError(error);
      } finally {
        this.isLoading = false;
      }
    },
    validateResponseData(data) {
      const requiredFields = ['status', 'predictions'];
      const missingFields = requiredFields.filter(field => !(field in data));

      if (missingFields.length > 0) {
        throw new Error(`无效的API响应结构，缺少字段: ${missingFields.join(', ')}`);
      }

      if (data.status !== 'success' && data.status !== 'error') {
        throw new Error(`无效的状态值: ${data.status}`);
      }

      if (data.status === 'success') {
        if (!Array.isArray(data.predictions) || data.predictions.length === 0) {
          throw new Error('预测数据格式错误或为空');
        }
        
        // 根据模型类型验证温度字段
        const field = this.selectedModel === 'LSTM' 
          ? this.lstmTempField 
          : this.selectedTarget;
          
        const hasValidTemp = data.predictions.some(item => item[field] !== undefined);
        
        if (!hasValidTemp) {
          throw new Error(`预测数据中缺少${field}字段`);
        }
      }
    },
    processResponseData(data) {
      this.apiResponse = {
        ...data,
        requested_days: this.selectedModel === 'Ensemble' ? this.predictionDays : 90
      };
      
      // 如果需要，可以在这里进一步处理LSTM数据格式
      if (this.selectedModel === 'LSTM') {
        console.log('处理后的LSTM数据:', this.apiResponse.predictions);
      }
    },
    renderTemperatureChart() {
      if (!this.chartInstance || !this.isChartDataReady || this.normalizedPredictions.length === 0) {
        console.log('Chart not ready or no data to render');
        return;
      }

      const chartData = this.normalizedPredictions;
      
      // 调试输出：检查数据是否正确
      console.log('Rendering chart with data:', chartData);

      const option = {
        title: {
          text: `桂林市未来${chartData.length}天${this.selectedModel === 'LSTM' ? '平均' : this.selectedTarget === 'guilin_max' ? '最高' : '最低'}温度预测`,
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333'
          },
          subtext: `数据更新时间: ${dayjs().format('YYYY-MM-DD HH:mm')}`,
          subtextStyle: {
            fontSize: 12,
            color: '#999'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: params => {
            const date = dayjs(params[0].axisValue).format('YYYY年MM月DD日');
            const temp = params[0].data;
            return `
              <div style="font-weight:bold;margin-bottom:5px">${date}</div>
              <div style="display:flex;align-items:center">
                <span style="display:inline-block;width:10px;height:10px;background:#36a3f7;margin-right:5px"></span>
                ${this.selectedModel === 'LSTM' ? '平均' : this.selectedTarget === 'guilin_max' ? '最高' : '最低'}温度: 
                <span style="color:#36a3f7;font-weight:bold;margin-left:5px">${temp}°C</span>
              </div>
            `;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '12%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: chartData.map(item => item.date),
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            color: '#666',
            rotate: 45,
            formatter: (value, index) => {
              const interval = Math.ceil(chartData.length / 10);
              return index % interval === 0 ? value : '';
            }
          },
          axisTick: {
            alignWithLabel: true,
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '温度 (°C)',
          nameTextStyle: {
            color: '#666',
            padding: [0, 0, 0, 40]
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            color: '#666',
            formatter: '{value}°C'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          }
        },
        series: [
          {
            name: this.selectedModel === 'LSTM' ? '平均温度' : this.selectedTarget === 'guilin_max' ? '最高温度' : '最低温度',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            data: chartData.map(item => item.temperature),
            itemStyle: {
              color: '#36a3f7',
              emphasis: {
                color: '#ff0000',
                borderColor: '#ff0000',
                borderWidth: 2
              }
            },
            lineStyle: {
              width: 3,
              color: '#36a3f7'
            },
            emphasis: {
              focus: 'series',
              itemStyle: {
                color: '#ff0000'
              }
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(54, 163, 247, 0.5)' },
                { offset: 1, color: 'rgba(54, 163, 247, 0.1)' }
              ])
            },
            markPoint: {
              data: [
                { type: 'max', name: '最高温' },
                { type: 'min', name: '最低温' }
              ],
              label: {
                color: '#000',
                backgroundColor: 'transparent',
                padding: [3, 5],
                borderRadius: 4
              }
            }
          }
        ],
        animationDuration: 1000
      };

      this.chartInstance.setOption(option, true);
    },
    // 提取预测数据的年份范围
    getPredictionYearsRange() {
      if (!this.hasValidData) return null;

      const dates = this.normalizedPredictions.map(item => item.date);
      if (dates.length === 0) return null;

      // 找到预测数据中的最早和最晚日期
      const sortedDates = dates.sort((a, b) => dayjs(a).diff(dayjs(b)));
      const earliestDate = dayjs(sortedDates[0]);
      const latestDate = dayjs(sortedDates[sortedDates.length - 1]);

      // 返回预测数据的年份范围
      return {
        startYear: earliestDate.year(),
        endYear: latestDate.year()
      };
    },
    // 获取预测年份之前的4年
    getHistoricalYears() {
      const predictionYears = this.getPredictionYearsRange();
      if (!predictionYears) return [];

      // 使用预测数据的起始年份作为基准
      const baseYear = predictionYears.startYear;

      // 计算前4年的年份数组
      return [
        (baseYear - 4).toString(),
        (baseYear - 3).toString(),
        (baseYear - 2).toString(),
        (baseYear - 1).toString()
      ];
    },
    // 初始化历史数据年份的颜色
    initHistoricalChartColors() {
      const years = this.getHistoricalYears();
      const colors = ['#67c23a', '#e6a23c', '#3e78d1', '#909399'];

      this.historicalChartColors = {};
      years.forEach((year, index) => {
        this.historicalChartColors[year] = colors[index % colors.length];
      });
    },
    async fetchHistoricalData() {
      if (!this.selectedMonth) return;

      this.isLoadingHistorical = true;
      this.error = '';

      // 初始化历史年份和颜色
      this.initHistoricalChartColors();

      try {
        const [year, month] = this.selectedMonth.split('-');
        // 根据模型类型选择历史数据字段
        const fields = this.selectedModel === 'LSTM' 
          ? 'guilin_temp,record_date' 
          : this.selectedTarget === 'guilin_max' 
            ? 'guilin_max,record_date' 
            : 'guilin_min,record_date';

        // 获取历史年份
        const historicalYears = this.getHistoricalYears();

        // 获取历史数据（前4年）
        const historicalData = await getHistoricalWeatherForPredictionComparison(
          parseInt(year),
          parseInt(month),
          fields,
          historicalYears
        );

        // 处理历史数据
        this.historicalData = Object.entries(historicalData).reduce((acc, [year, response]) => {
          if (response.code === 200 && response.data && response.data.length > 0) {
            // 根据模型类型选择历史数据字段
            const field = this.selectedModel === 'LSTM' 
              ? 'guilin_temp' 
              : this.selectedTarget === 'guilin_max' 
                ? 'guilin_max' 
                : 'guilin_min';
                
            acc[year] = response.data.map(item => ({
              date: dayjs(item.record_date).format('YYYY-MM-DD'),
              temperature: parseFloat(item[field])
            })).sort((a, b) => dayjs(a.date).diff(dayjs(b.date)));
          }
          return acc;
        }, {});

        // 提取当前月份的预测数据
        this.extractCurrentMonthPredictions();
        
        // 确保DOM更新后再渲染图表
        this.$nextTick(() => {
          this.renderHistoricalChart();
        });

      } catch (error) {
        this.handleRequestError(error);
      } finally {
        this.isLoadingHistorical = false;
      }
    },

    // 修改后的 extractCurrentMonthPredictions 方法
    extractCurrentMonthPredictions() {
      if (!this.hasValidData || !this.selectedMonth) return;

      const [selectedYear, selectedMonth] = this.selectedMonth.split('-');
      // 根据模型类型选择预测数据字段
      const field = this.selectedModel === 'LSTM' 
        ? this.lstmTempField 
        : this.selectedTarget;
          
      const currentMonthPredictions = this.normalizedPredictions
        .filter(item => {
          const itemDate = dayjs(item.date);
          return (
            itemDate.year().toString() === selectedYear &&
            (itemDate.month() + 1).toString().padStart(2, '0') === selectedMonth
          );
        });

      // 将预测数据添加到历史数据中
      this.historicalData['prediction'] = currentMonthPredictions;
    },

    // 修改后的 prepareSeriesData 方法
    prepareSeriesData(data, xAxisData) {
      const dateTempMap = new Map();

      // 处理数据，确保日期格式一致
      data.forEach(item => {
        const dateKey = dayjs(item.date).format('MM-DD');
        dateTempMap.set(dateKey, item.temperature);
      });

      // 填充缺失的日期
      return xAxisData.map(date => {
        const value = dateTempMap.get(date);
        return value !== undefined ? value : null;
      });
    },

    // 修改后的 renderHistoricalChart 方法
    renderHistoricalChart() {
      if (!this.historicalChartInstance || !this.selectedMonth) return;

      const [year, month] = this.selectedMonth.split('-');
      const monthName = dayjs(`${year}-${month}-01`).format('MM月');

      // 生成x轴数据（该月的所有日期）
      const daysInMonth = dayjs(`${year}-${month}`).daysInMonth();
      const xAxisData = Array.from({ length: daysInMonth }, (_, i) =>
        dayjs(`${year}-${month}-${i + 1}`).format('MM-DD')
      );

      // 准备系列数据
      const series = [];

      // 添加预测数据系列
      if (this.historicalData['prediction'] && this.historicalData['prediction'].length > 0) {
        const predictionData = this.prepareSeriesData(this.historicalData['prediction'], xAxisData);
        series.push({
          name: '预测数据',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          data: predictionData,
          itemStyle: {
            color: this.predictionColor,
            emphasis: {
              borderWidth: 2
            }
          },
          lineStyle: {
            width: 3,
            color: this.predictionColor,
            type: 'dashed'
          },
          emphasis: {
            focus: 'series'
          },
          z: 10
        });
      }

      // 添加历史数据系列
      Object.entries(this.historicalData).forEach(([year, data]) => {
        if (year === 'prediction') return;

        const seriesData = this.prepareSeriesData(data, xAxisData);
        if (seriesData.some(value => value !== null)) {
          series.push({
            name: `${year}年`,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            data: seriesData,
            itemStyle: {
              color: this.historicalChartColors[year] || '#909399',
              emphasis: {
                borderWidth: 2
              }
            },
            lineStyle: {
              width: 2,
              color: this.historicalChartColors[year] || '#909399'
            },
            emphasis: {
              focus: 'series'
            }
          });
        }
      });

      const targetName = this.selectedModel === 'LSTM' 
        ? '平均温度' 
        : this.selectedTarget === 'guilin_max' 
          ? '最高温度' 
          : '最低温度';

      // 配置图表选项
      const option = {
        title: {
          text: `桂林市历史${monthName}${targetName}与预测对比`,
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333'
          },
          subtext: `数据更新时间: ${dayjs().format('YYYY-MM-DD HH:mm')}`,
          subtextStyle: {
            fontSize: 12,
            color: '#999'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: params => {
            let result = `<div style="font-weight:bold;margin-bottom:5px">${params[0].axisValue}</div>`;
            params.forEach(param => {
              if (param.data !== null) {
                result += `
                  <div style="display:flex;align-items:center">
                    <span style="display:inline-block;width:10px;height:10px;background:${param.color};margin-right:5px"></span>
                    ${param.seriesName}: <span style="color:${param.color};font-weight:bold;margin-left:5px">${param.data}°C</span>
                  </div>
                `;
              }
            });
            return result;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '12%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            color: '#666',
            rotate: 45,
            formatter: (value, index) => {
              // 控制x轴标签显示密度，避免过于拥挤
              const interval = Math.ceil(xAxisData.length / 10);
              return index % interval === 0 ? value : '';
            }
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '温度 (°C)',
          nameTextStyle: {
            color: '#666',
            padding: [0, 0, 0, 40]
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            color: '#666',
            formatter: '{value}°C'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          }
        },
        series: series,
        animationDuration: 1000
      };

      this.historicalChartInstance.setOption(option, true);
    },

    handleRequestError(error) {
      console.error('API请求错误:', error);

      let errorMessage = '获取数据失败';
      let errorDetails = '';

      if (error.response) {
        switch (error.response.status) {
          case 400:
            errorMessage = '请求参数错误';
            errorDetails = '请检查请求参数是否正确，例如预测天数等';
            break;
          case 404:
            errorMessage = 'API接口不存在';
            errorDetails = '请检查API地址是否正确，确保路径没有拼写错误';
            break;
          case 500:
            errorMessage = '服务器内部错误';
            errorDetails = '服务器处理请求时发生错误，请联系管理员排查问题';
            break;
          case 504:
            errorMessage = '请求超时';
            errorDetails = '服务器响应超时，请稍后重试，或者检查网络连接是否稳定';
            break;
          default:
            errorMessage = `服务器错误 (${error.response.status})`;
            errorDetails = error.response.data?.message || '未知服务器错误，请尝试重新获取数据';
        }
      } else if (error.message) {
        if (error.message.includes('timeout')) {
          errorMessage = '请求超时';
          errorDetails = '连接服务器超时，请检查网络连接是否稳定，或稍后再试';
        } else if (error.message.includes('Network')) {
          errorMessage = '网络错误';
          errorDetails = '无法连接到服务器，请检查网络连接是否正常，或确认API服务是否已启动';
        } else {
          errorDetails = error.message;
        }
      } else {
        errorDetails = '发生未知错误，请刷新页面后重试';
      }

      this.$message({
        type: 'error',
        message: `${errorMessage}: ${errorDetails}`,
        duration: 5000,
        showClose: true
      });

      this.apiResponse.status = 'error';
      this.error = `${errorMessage}: ${errorDetails}`;
    },
    handleDaysChange(value) {
      this.predictionDays = Math.max(1, Math.min(180, value));

      if (value < 1 || value > 180) {
        this.$message({
          type: 'error',
          message: '预测天数必须在1-180天之间',
          duration: 3000
        });
      }
    },
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
      if (this.historicalChartInstance) {
                this.historicalChartInstance.resize();
      }
    }
  }
};
</script>

<style scoped lang="scss">
.temperature-forecast-container {
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
  
  // 确保内容不被挤压
  max-width: 1600px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
  }
  
  .controls {
    display: flex;
    gap: 15px; // 增加控件间距
    align-items: center;
    flex-wrap: wrap; // 允许控件换行
    
    // 调整选择器和输入框宽度
    .el-select {
      min-width: 150px; // 增加最小宽度
      width: auto;
    }
    
    .el-input-number {
      min-width: 100px; // 增加最小宽度
      width: auto;
    }
    
    .el-button {
      min-width: 100px; // 确保按钮有足够宽度
    }
  }
}

.content-wrapper {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.response-section {
  margin-bottom: 20px;
}

.response-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  
  h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
  }
  
  .response-meta {
    display: flex;
    gap: 10px;
    align-items: center;
  }
  
  .predicted_days {
    margin-left: 10px;
    font-size: 14px;
    color: #606266;
  }
}

.response-data {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  
  @media (max-width: 992px) { // 调整断点
    grid-template-columns: 1fr;
  }
}

.forecast-details-container,
.monthly-average-container {
  .el-collapse-item__header {
    font-weight: bold;
  }
  
  // 确保表格在小屏幕上可滚动
  .el-table {
    overflow-x: auto;
    display: block;
  }
}

.chart-section {
  margin-bottom: 30px;
  
  .chart-container {
    height: 450px; // 增加图表高度
    margin-bottom: 15px;
    width: 100%; // 确保图表占满容器
  }
  
  .chart-legend {
    display: flex;
    gap: 20px;
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .legend-item {
    display: flex;
    align-items: center;
    gap: 5px;
    
    .legend-color {
      width: 10px;
      height: 10px;
      border-radius: 50%;
    }
    
    .legend-text {
      font-size: 14px;
      color: #606266;
    }
  }
}

.historical-comparison-section {
  .chart-controls {
    display: flex;
    gap: 15px; // 增加控件间距
    margin-bottom: 20px;
    align-items: center;
    flex-wrap: wrap; // 允许控件换行
    
    .el-select {
      min-width: 150px; // 增加最小宽度
      width: auto;
    }
    
    .el-button {
      min-width: 100px; // 确保按钮有足够宽度
    }
  }
  
  .chart-container {
    height: 450px; // 增加图表高度
    margin-bottom: 15px;
    width: 100%; // 确保图表占满容器
  }
  
  .chart-legend {
    display: flex;
    gap: 20px;
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .legend-item {
    display: flex;
    align-items: center;
    gap: 5px;
    
    .legend-color {
      width: 10px;
      height: 10px;
      border-radius: 50%;
    }
    
    .legend-text {
      font-size: 14px;
      color: #606266;
    }
    
    &.prediction {
      .legend-color {
        background-color: #ff0000;
      }
    }
  }
}

.error-message {
  margin-bottom: 20px;
}

// 响应式调整
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    
    h2 {
      margin-bottom: 15px;
    }
    
    .controls {
      width: 100%;
    }
  }
  
  .chart-section .chart-container,
  .historical-comparison-section .chart-container {
    height: 350px; // 小屏幕上减小图表高度
  }
}

@media (max-width: 576px) {
  .controls,
  .chart-controls {
    gap: 10px;
    
    .el-select,
    .el-input-number {
      min-width: 120px; // 超小屏幕上进一步减小最小宽度
    }
  }
}
</style>